import torch
import matplotlib.pyplot as plt
import matplotlib

x_data = torch.Tensor([[1.0],
                      [2.0],
                      [3.0]])

y_data = torch.Tensor([[2.0],
                       [4.0],
                       [6.0]])

class LinearModel(torch.nn.Module): # 定义的模型必须继承自 torch.nn.Module
    def __init__(self):
        super(LinearModel, self).__init__() # 继承父类
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x): # 模型中必须定义 forward 函数
        y_pred = self.linear(x)
        return y_pred

model = LinearModel()
criterion = torch.nn.MSELoss(reduction="mean") # 定义损失函数
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 定义优化器

epoches = 100
loss_list = []
epoch_list = []

for epoch in range(epoches):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print("epoch:", epoch, "loss:", loss.item())
    loss_list.append(loss.item())
    epoch_list.append(epoch)

    optimizer.zero_grad()  # 梯度清零
    loss.backward()
    optimizer.step()  # 更新梯度

print("w = ", model.linear.weight.item(), " b = ", model.linear.bias.item())

x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print("y_test: ", y_test.data)

matplotlib.use("TkAgg")
plt.plot(epoch_list, loss_list)
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()